package cn.tedu.cs.baking.controller;

import cn.tedu.cs.baking.common.ex.BusinessException;
import cn.tedu.cs.baking.dao.UserMapper;
import cn.tedu.cs.baking.pojo.dto.UserDTO;
import cn.tedu.cs.baking.pojo.po.User;
import cn.tedu.cs.baking.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/list")
    @ApiOperation("用户列表")
    public List<UserVO> getUserList(
            @RequestParam(required = true,defaultValue = "1") Integer pageCurrent,
            @RequestParam(required = true,defaultValue = "10") Integer pageSize){
        int index = pageSize*(pageCurrent-1);
        List<UserVO> list = userMapper.getList(index,pageSize);
        return list;
    }

    @PostMapping("insert")
    @ApiOperation("新增用户")
    public void insert(@Valid @RequestBody UserDTO userDTO){
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setIsAdmin(0);
        user.setCreateTime(new Date());
        int rows = userMapper.insert(user);
        if (rows != 1){
            System.out.println("插入数据失败!!");
        }
    }

    @GetMapping("getByUserId")
    @ApiOperation("用户详情")
    public User selectByUserId(Long id){
        return userMapper.selectByPrimaryKey(id);
    }

    @PostMapping("delete/{id}")
    @ApiOperation("删除用户")
    public void deleteById(@PathVariable Long id) throws BusinessException {
        int rows = userMapper.deleteById(id);
        if (rows != 1){
            throw new BusinessException("删除用户失败!");
        }
    }

    @PostMapping("update")
    @ApiOperation("用户更新")
    public void updateById(@Valid @RequestBody User user){

        userMapper.updateByPrimaryKeySelective(user);
    }
}
